package com.dongdongshop.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.User;
import com.dongdongshop.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

//登录与授权逻辑编写的位置
public class LoginRealm extends AuthorizingRealm {

    @Reference
    private UserService userService;

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    //登录方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法");
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        //根据用户名查询用户这是否存在
        User user = userService.getByName(username);
        if(user == null){
            return null;
        }
        //第一个,登陆成功后,用户存放到session
        //第二个,数据库里的密码
        //第三个数据库的盐
        //第四个,登陆成功后,用户的账户名
        return new SimpleAuthenticationInfo(user,user.getPwd(), ByteSource.Util.bytes(user.getSalt()),user.getName());
    }
}
